import os
import glob
import logging
from datetime import datetime

def setup_ros_logging(launch_file, log_dir, max_files=50):
    """为ROS进程设置日志重定向"""
    # 创建启动文件对应的日志目录
    # launch_file = Path(launch_file).stem
    launch_log_dir = os.path.join(log_dir, launch_file)
    os.makedirs(launch_log_dir, exist_ok=True)
    
    # 清理旧的日志文件（保留最近max_files个）
    log_files = glob.glob(os.path.join(launch_log_dir, '*.log'))
    log_files.sort(key=os.path.getmtime)
    
    while len(log_files) >= max_files:
        oldest_file = log_files.pop(0)
        try:
            os.remove(oldest_file)
        except:
            pass
    
    # 生成新的日志文件名
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    log_filename = f"{launch_file}_{timestamp}.log"
    log_path = os.path.join(launch_log_dir, log_filename)
    
    return open(log_path, 'w'), log_path